/**
 * ReportGear(2011)
 */
package com.reportgear.report.view.grid;

import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;

import javax.swing.JScrollBar;

import com.reportgear.report.view.JWorksheet;

/**
 * Grid滚动条
 * 
 * @version 1.0 2011-3-14
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since Report 1.0
 * 
 */
public class DynamicScrollBar extends JScrollBar {

	/**
	 * UID
	 */
	private static final long serialVersionUID = -2775143151103635774L;
	// 对应工作簿
	private JWorksheet workSheet;

	public DynamicScrollBar(int orientation, JWorksheet workSheet) {
		super(orientation);

		this.workSheet = workSheet;
		this.setMinimum(0);
		this.setUnitIncrement(1);
		this.setBlockIncrement(3);

		this.addComponentListener(new ComponentListener() {

			public void componentResized(ComponentEvent componentevent) {
				adjustValues();
			}

			public void componentMoved(ComponentEvent componentevent) {
				adjustValues();
			}

			public void componentShown(ComponentEvent componentevent) {
				adjustValues();
			}

			public void componentHidden(ComponentEvent componentevent) {
				adjustValues();
			}

			private void adjustValues() {
				setValue(getValue());
			}
		});
	}

	@Override
	public int getVisibleAmount() {
		if (this.workSheet == null) {
			return 0;
		}
		if (orientation == JScrollBar.VERTICAL) {
			return this.getVerticalExtent(this.getValue());
		} else {
			return this.getHorizontalExtent(this.getValue());
		}
	}

	@Override
	public void setValue(int value) {
		super.setValue(value);
		
		if (this.workSheet == null) {
			return;
		}

		if (orientation == JScrollBar.VERTICAL) {
			this.workSheet.setVertBeginValue(this.getValue());
		} else {
			this.workSheet.setHoriBeginValue(this.getValue());
		}
		
		this.workSheet.refresh();
	}

	private int getVerticalExtent(int index) {
		int extend = this.workSheet.getVertBeginValue() + this.workSheet.getVertValueExtend();

		this.setMaximum(extend);

		return extend - index - 2;
	}

	private int getHorizontalExtent(int index) {
		int extend = this.workSheet.getHoriBeginValue() + this.workSheet.getHoriValueExtend();

		this.setMaximum(extend);

		return extend - index - 2;
	}
}